import * as vscode from 'vscode';
import { DifyService, ReviewResult } from './difyService';
import * as child_process from 'child_process';
import * as path from 'path';
import { Logger } from './logger';
import { RemoteConfig, ConfigService } from './configService';
import { AuthService } from './authService';

export class ScmInterceptor {
    private difyService: DifyService;
    private authService: AuthService;
    private disposables: vscode.Disposable[] = [];
    private isReviewPassed: boolean = false;
    private reviewResult: any = null;
    private commitButtonDisabled: boolean = false;
    private statusBarItem: vscode.StatusBarItem;
    private isReviewing: boolean = false;
    // 最大diff长度由配置注入
    private readonly maxDiffLength: number;
    private logger = Logger.getInstance();

    constructor(difyService: DifyService, config: RemoteConfig, authService: AuthService) {
        this.difyService = difyService;
        this.authService = authService;
        this.maxDiffLength = config.maxDiffLength;
        this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 100);
        this.statusBarItem.text = "$(light-bulb) Dify 代码审查";
        this.statusBarItem.tooltip = "点击开始 Dify AI 代码审查";
        this.statusBarItem.command = 'dify-code-review.startReview';
    }

    public initialize() {
        // 显示状态栏
        this.statusBarItem.show();
        
        // 拦截Git commit操作
        this.interceptGitCommit();
        
        // 注册手动审查命令
        this.registerCommands();
        
        // 初始状态：未审查
        this.setReviewStatus('pending', '等待代码审查');
    }

    private registerCommands() {
        // 只注册 startReview 命令，所有入口都用这个
        const startReviewCommand = vscode.commands.registerCommand('dify-code-review.startReview', async () => {
            try {
                const config: RemoteConfig = await ConfigService.getConfig();
                this.difyService.updateConfig(config);
                await this.performMandatoryCodeReview();
            } catch (e) {
                vscode.window.showErrorMessage('无法获取插件配置，请检查网络连接或VPN设置后重试。');
            }
        });
        this.disposables.push(startReviewCommand);
    }

    private interceptGitCommit() {
        // 使用命令执行器来拦截git.commit命令
        const originalExecuteCommand = vscode.commands.executeCommand;
        
        // 重写executeCommand来拦截git.commit
        const interceptExecuteCommand = async (command: string, ...args: any[]) => {
            if (command === 'git.commit') {
                this.logger.info('拦截到git.commit命令');
                if (!this.isReviewPassed) {
                    this.logger.warn('未通过Dify审查，阻止提交');
                    vscode.window.showWarningMessage('请先通过 Dify 代码审查后再提交代码');
                    await this.performMandatoryCodeReview();
                    return;
                }
                this.logger.info('Dify审查已通过，允许提交');
                this.setReviewStatus('pending', '正在提交...');
                const result = await originalExecuteCommand(command, ...args);
                this.setReviewStatus('pending', '等待代码审查');
                this.isReviewPassed = false;
                return result;
            }
            return originalExecuteCommand(command, ...args);
        };

        // 替换全局的executeCommand
        (vscode.commands as any).executeCommand = interceptExecuteCommand;
        
        // 保存原始函数以便恢复
        this.disposables.push({
            dispose: () => {
                (vscode.commands as any).executeCommand = originalExecuteCommand;
            }
        });
    }


    private setReviewStatus(status: 'pending' | 'reviewing' | 'passed' | 'failed', message: string) {
        switch (status) {
            case 'pending':
                this.statusBarItem.text = "$(light-bulb) Dify 代码审查";
                this.statusBarItem.tooltip = "点击开始 Dify AI 代码审查";
                this.statusBarItem.backgroundColor = undefined;
                break;
            case 'reviewing':
                this.statusBarItem.text = "$(sync~spin) 正在审查...";
                this.statusBarItem.tooltip = "正在进行 Dify AI 代码审查";
                this.statusBarItem.backgroundColor = new vscode.ThemeColor('statusBarItem.prominentBackground');
                break;
            case 'passed':
                this.statusBarItem.text = "$(check) 审查通过";
                this.statusBarItem.tooltip = "代码审查通过，可以提交";
                this.statusBarItem.backgroundColor = new vscode.ThemeColor('statusBarItem.successBackground');
                break;
            case 'failed':
                this.statusBarItem.text = "$(error) 审查未通过";
                this.statusBarItem.tooltip = "代码审查未通过，请修改后重新审查";
                this.statusBarItem.backgroundColor = new vscode.ThemeColor('statusBarItem.errorBackground');
                break;
        }
    }

    public async performMandatoryCodeReview() {
        // 登录检测
        const user = await this.authService.getCurrentUser();
        if (!user) {
            const login = await vscode.window.showInformationMessage('请先登录后再进行代码审查', '登录');
            if (login === '登录') {
                try {
                    await this.authService.login();
                } catch (e: any) {
                    vscode.window.showErrorMessage('登录失败: ' + e.message);
                    return;
                }
            } else {
                return;
            }
        }
        if (this.isReviewing) {
            this.logger.warn('代码审查正在进行，重复请求被忽略');
            vscode.window.showWarningMessage('代码审查正在进行，请稍候...');
            return;
        }
        this.isReviewing = true;
        try {
            this.logger.info('开始执行强制代码审查');
            this.setReviewStatus('reviewing', '正在进行代码审查...');
            await vscode.window.withProgress({
                location: vscode.ProgressLocation.Notification,
                title: "正在进行 Dify 代码审查...",
                cancellable: false
            }, async (progress: vscode.Progress<{ increment?: number; message?: string }>) => {
                progress.report({ increment: 0, message: "分析代码变更..." });
                const changedFiles = await this.getChangedFiles();
                this.logger.debug(`变更文件数: ${changedFiles.length}`);
                if (changedFiles.length === 0) {
                    this.logger.info('未检测到代码变更，无需审查');
                    vscode.window.showInformationMessage('未检测到代码变更，无需审查。');
                    this.isReviewPassed = true;
                    this.setReviewStatus('passed', '无需审查');
                    return;
                }
                progress.report({ increment: 50, message: "调用 Dify API 进行分片审查..." });
                const result = await this.performChunkedCodeReview();
                this.logger.info(`Dify审查结果: pass=${result.pass}`);
                this.reviewResult = result;
                progress.report({ increment: 100, message: "处理审查结果..." });
                await this.handleReviewResult(result);
            });
        } catch (error) {
            this.logger.error('performMandatoryCodeReview异常', error as Error);
            vscode.window.showErrorMessage('代码审查失败: ' + (error instanceof Error ? error.message : error));
        } finally {
            this.isReviewing = false;
        }
    }

    private async handleReviewResult(result: any) {
        if (result.pass) {
            this.logger.info('代码审查通过');
            this.isReviewPassed = true;
            this.setReviewStatus('passed', '审查通过');
            if (result.commitMessage) {
                this.logger.info('自动提交: ' + result.commitMessage);
                await this.updateCommitMessage(result.commitMessage);
                await this.executeGitCommitWithMessage(result.commitMessage);
                vscode.window.showInformationMessage(`✅ 代码审查通过，已自动提交！Commit message: ${result.commitMessage}`);
            } else {
                vscode.window.showInformationMessage('✅ 代码审查通过！');
            }
        } else {
            this.logger.warn('代码审查未通过: ' + result.reason);
            this.isReviewPassed = false;
            this.setReviewStatus('failed', '审查未通过');
            await this.showReviewIssues(result);
            vscode.window.showErrorMessage('❌ 代码审查未通过，无法提交代码。');
        }
    }

    private async showReviewIssues(result: any) {
        const reason = result.reason || '代码审查未通过';
        
        // 创建详细的问题报告
        const issueReport = `## 代码审查未通过

**问题描述：**
${reason}

**建议操作：**
1. 请根据上述问题修改代码
2. 修改完成后重新进行代码审查
3. 审查通过后才能提交代码

**审查详情：**
- 审查时间: ${new Date().toLocaleString()}
- 审查状态: ❌ 未通过

**修改建议：**
请根据Dify AI的建议修改代码，确保代码质量和安全性。`;

        // 显示模态框
        const document = await vscode.workspace.openTextDocument({
            content: issueReport,
            language: 'markdown'
        });
        
        await vscode.window.showTextDocument(document, vscode.ViewColumn.One);
        
        // 同时显示通知
        vscode.window.showErrorMessage(`❌ 代码审查未通过: ${reason}`);
    }

    private async executeGitCommit() {
        try {
            // 获取当前的commit message
            const scm = vscode.scm.inputBox;
            const commitMessage = scm?.value || '';
            
            if (!commitMessage.trim()) {
                vscode.window.showErrorMessage('Commit message 不能为空');
                return;
            }

            // 执行Git commit命令
            const terminal = vscode.window.createTerminal('Git Commit');
            terminal.sendText(`git commit -m "${commitMessage.replace(/"/g, '\\"')}"`);
            terminal.show();
            
            vscode.window.showInformationMessage('✅ 代码已成功提交！');
            
        } catch (error) {
            vscode.window.showErrorMessage(`提交失败: ${error instanceof Error ? error.message : '未知错误'}`);
        }
    }

    private async getChangedFiles(): Promise<string[]> {
        try {
            const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
            if (!workspaceFolder) {
                return [];
            }

            // 执行 git status --porcelain 获取变更文件列表
            const result = await this.executeGitCommand('status', '--porcelain');
            
            if (!result) {
                return [];
            }

            // 解析 git status 输出，提取文件路径
            const files: string[] = [];
            const lines = result.split('\n').filter(line => line.trim());
            
            for (const line of lines) {
                // git status --porcelain 格式: XY PATH
                // 其中 XY 是状态码，PATH 是文件路径
                const status = line.substring(0, 2);
                const filePath = line.substring(3).trim();
                
                // 只处理修改的文件（M）、新文件（A）、删除的文件（D）
                if (status.includes('M') || status.includes('A') || status.includes('D')) {
                    files.push(filePath);
                }
            }

            return files;
        } catch (error) {
            this.logger.error('获取变更文件失败', error as Error);
            return [];
        }
    }

    private async getDiffContent(): Promise<{ filePath: string; diffContent: string }[]> {
        try {
            const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
            if (!workspaceFolder) {
                return [];
            }

            // 获取暂存区diff
            const stagedResult = await this.executeGitCommand('diff', '--staged');
            if (!stagedResult) return [];

            // 拆分为每个文件的diff
            const diffs = stagedResult.split(/^diff --git /m).filter(Boolean);
            let fileDiffs: { filePath: string; diffContent: string }[] = [];
            
            for (const diff of diffs) {
                // 还原diff头
                const fullDiff = 'diff --git ' + diff;
                
                // 提取文件路径
                const fileMatch = fullDiff.match(/^diff --git a\/(.+) b\/(.+)$/m);
                if (!fileMatch) continue;
                
                const filePath = fileMatch[1]; // 使用 a/ 路径作为文件路径
                
                // 检查是否为rename
                const renameFrom = fullDiff.match(/^rename from (.+)$/m);
                const renameTo = fullDiff.match(/^rename to (.+)$/m);
                
                if (renameFrom && renameTo) {
                    fileDiffs.push({
                        filePath: renameTo[1], // 使用新文件名
                        diffContent: `文件重命名:
- 原文件名: ${renameFrom[1]}
- 新文件名: ${renameTo[1]}
`
                    });
                } else {
                    fileDiffs.push({
                        filePath,
                        diffContent: fullDiff
                    });
                }
            }
            
            return fileDiffs;
        } catch (error) {
            this.logger.error('获取Git diff失败', error as Error);
            return [];
        }
    }

    // 新增：分片审查方法
    private async performChunkedCodeReview(): Promise<ReviewResult> {
        this.logger.info('开始分片代码审查');
        
        try {
            // 获取按文件分组的 diff 内容
            const fileDiffs = await this.getDiffContent();
            
            if (fileDiffs.length === 0) {
                this.logger.info('未检测到代码变更，无需审查');
                return {
                    pass: true,
                    reason: '无需审查',
                    commitMessage: ''
                };
            }

            this.logger.info(`检测到 ${fileDiffs.length} 个文件的变更，开始分片审查`);

            // 检查文件数量限制
            const MAX_FILES_LIMIT = 15; // 固定为15个文件限制
            if (fileDiffs.length > MAX_FILES_LIMIT) {
                const message = `检测到 ${fileDiffs.length} 个文件变更，超过建议的 ${MAX_FILES_LIMIT} 个文件限制。建议分批次提交以提高审查效率。`;
                console.log(`=== 文件数量警告 ===`);
                console.log(message);
                console.log('---');
                
                vscode.window.showWarningMessage(message);
                
                this.logger.info('文件数量过多，停止审查');
                return {
                    pass: false,
                    reason: `文件数量过多 (${fileDiffs.length} > ${MAX_FILES_LIMIT})，建议分批次提交`,
                    commitMessage: ''
                };
            }

            // 文件类型分析和优先级排序
            const fileTypeStats = new Map<string, number>();
            const priorityExtensions = ['.ts', '.js', '.tsx', '.jsx', '.vue', '.py', '.java', '.cpp', '.c', '.cs'];
            
            fileDiffs.forEach(fileDiff => {
                const ext = path.extname(fileDiff.filePath).toLowerCase();
                fileTypeStats.set(ext, (fileTypeStats.get(ext) || 0) + 1);
            });
            
            // 按优先级排序文件（代码文件优先）
            fileDiffs.sort((a, b) => {
                const extA = path.extname(a.filePath).toLowerCase();
                const extB = path.extname(b.filePath).toLowerCase();
                const priorityA = priorityExtensions.indexOf(extA);
                const priorityB = priorityExtensions.indexOf(extB);
                
                if (priorityA !== -1 && priorityB !== -1) {
                    return priorityA - priorityB; // 代码文件按优先级排序
                } else if (priorityA !== -1) {
                    return -1; // 代码文件优先
                } else if (priorityB !== -1) {
                    return 1;
                }
                return 0; // 其他文件保持原顺序
            });
            
            // 打印拆分结果摘要
            console.log('=== 文件拆分结果 ===');
            console.log(`总共 ${fileDiffs.length} 个文件需要审查:`);
            console.log('文件类型统计:');
            fileTypeStats.forEach((count, ext) => {
                console.log(`  ${ext}: ${count} 个文件`);
            });
            console.log('---');
            fileDiffs.forEach((fileDiff, index) => {
                const ext = path.extname(fileDiff.filePath).toLowerCase();
                const isPriority = priorityExtensions.includes(ext);
                console.log(`  ${index + 1}. ${fileDiff.filePath} (${fileDiff.diffContent.length} 字符) ${isPriority ? '[代码文件]' : ''}`);
            });
            console.log('---');

            // 显示进度信息
            vscode.window.showInformationMessage(`开始审查 ${fileDiffs.length} 个文件的变更...`);

            // 对每个文件进行单独审查，添加进度显示
            const reviewResults = [];
            const startTime = Date.now();
            let totalSuccessCount = 0;
            let totalFailureCount = 0;
            
            for (let index = 0; index < fileDiffs.length; index++) {
                const fileDiff = fileDiffs[index];
                this.logger.debug(`审查文件 ${index + 1}/${fileDiffs.length}: ${fileDiff.filePath}`);
                
                // 更新状态栏显示当前审查进度
                this.setReviewStatus('reviewing', `审查中... (${index + 1}/${fileDiffs.length}) ${fileDiff.filePath}`);
                
                // 检查单个文件的 diff 内容长度限制
                const MAX_SINGLE_FILE_DIFF_LENGTH = 30000; // 固定为30KB限制
                if (fileDiff.diffContent.length > MAX_SINGLE_FILE_DIFF_LENGTH) {
                    const message = `文件 ${fileDiff.filePath} 的变更内容过大 (${fileDiff.diffContent.length} 字符 > ${MAX_SINGLE_FILE_DIFF_LENGTH} 字符)，建议分多次提交或减少单次变更量。`;
                    console.log(`=== 单文件大小警告 ===`);
                    console.log(message);
                    console.log('---');
                    
                    vscode.window.showWarningMessage(message);
                    
                    reviewResults.push({
                        filePath: fileDiff.filePath,
                        result: null,
                        success: false,
                        error: `文件变更内容过大 (${fileDiff.diffContent.length} > ${MAX_SINGLE_FILE_DIFF_LENGTH})`
                    });
                    continue; // 跳过这个文件，继续处理下一个
                }
                
                try {
                    const result = await this.difyService.reviewCode([fileDiff.filePath], fileDiff.diffContent);
                    reviewResults.push({
                        filePath: fileDiff.filePath,
                        result,
                        success: true
                    });
                    totalSuccessCount++;
                    this.logger.debug(`文件 ${fileDiff.filePath} 审查完成: ${result.pass ? '通过' : '未通过'}`);
                } catch (error) {
                    this.logger.error(`文件 ${fileDiff.filePath} 审查失败:`, error as Error);
                    
                    // 检查是否是长度问题导致的错误
                    let errorMessage = error instanceof Error ? error.message : '未知错误';
                    let shouldRetry = false;
                    
                    if (errorMessage.includes('too long') || errorMessage.includes('token limit')) {
                        errorMessage = `文件变更内容过大，超过 Dify API 的 token 限制 (${fileDiff.diffContent.length} 字符)，建议分多次提交或减少单次变更量。`;
                        console.log(`=== API 长度限制错误 ===`);
                        console.log(`文件: ${fileDiff.filePath}`);
                        console.log(`内容长度: ${fileDiff.diffContent.length} 字符`);
                        console.log(`错误信息: ${errorMessage}`);
                        console.log('---');
                        
                        vscode.window.showWarningMessage(`文件 ${fileDiff.filePath} 变更内容过大，超过 API 限制`);
                    } else if (errorMessage.includes('timeout') || errorMessage.includes('network') || errorMessage.includes('ECONNRESET')) {
                        // 网络相关错误，可以重试
                        shouldRetry = true;
                        errorMessage = `网络错误，正在重试... (${errorMessage})`;
                    }
                    
                    if (shouldRetry) {
                        // 简单重试机制
                        try {
                            console.log(`=== 重试审查文件 ===`);
                            console.log(`文件: ${fileDiff.filePath}`);
                            console.log('---');
                            
                            const retryResult = await this.difyService.reviewCode([fileDiff.filePath], fileDiff.diffContent);
                            reviewResults.push({
                                filePath: fileDiff.filePath,
                                result: retryResult,
                                success: true
                            });
                            this.logger.debug(`文件 ${fileDiff.filePath} 重试审查完成: ${retryResult.pass ? '通过' : '未通过'}`);
                            continue;
                        } catch (retryError) {
                            errorMessage = `重试失败: ${retryError instanceof Error ? retryError.message : '未知错误'}`;
                        }
                    }
                    
                    reviewResults.push({
                        filePath: fileDiff.filePath,
                        result: null,
                        success: false,
                        error: errorMessage
                    });
                    totalFailureCount++;
                }
            }
            
            // 分析审查结果
            const successfulReviews = reviewResults.filter(r => r.success);
            const failedReviews = reviewResults.filter(r => !r.success);
            const totalTime = Date.now() - startTime;
            
            // 输出性能统计
            console.log(`=== 审查性能统计 ===`);
            console.log(`总耗时: ${totalTime}ms`);
            console.log(`平均每文件: ${Math.round(totalTime / fileDiffs.length)}ms`);
            console.log(`成功: ${totalSuccessCount} 个文件`);
            console.log(`失败: ${totalFailureCount} 个文件`);
            console.log(`成功率: ${Math.round((totalSuccessCount / fileDiffs.length) * 100)}%`);
            console.log('---');
            
            if (failedReviews.length > 0) {
                this.logger.warn(`${failedReviews.length} 个文件审查失败`);
                failedReviews.forEach(f => {
                    this.logger.warn(`文件 ${f.filePath} 审查失败: ${f.error}`);
                });
            }

            // 检查审查结果并决定是否进入汇聚阶段
            this.logger.info(`分片审查完成: 成功 ${successfulReviews.length} 个文件, 失败 ${failedReviews.length} 个文件`);
            return await this.aggregateReviewResults(reviewResults);
            
        } catch (error) {
            this.logger.error('分片代码审查失败', error as Error);
            throw error;
        }
    }

    // 新增：汇聚审查结果
    private async aggregateReviewResults(reviewResults: any[]): Promise<ReviewResult> {
        const successfulReviews = reviewResults.filter(r => r.success);
        const failedReviews = reviewResults.filter(r => !r.success);
        
        // 如果所有文件都审查失败，返回失败结果
        if (successfulReviews.length === 0) {
            return {
                pass: false,
                reason: `所有文件审查失败: ${failedReviews.map(f => `${f.filePath}(${f.error})`).join(', ')}`,
                commitMessage: ''
            };
        }

        // 检查是否有任何文件审查未通过
        const failedChecks = successfulReviews.filter(r => !r.result.pass);
        
        if (failedChecks.length > 0) {
            // 有文件审查未通过，直接返回失败，不进行汇聚
            const reasons = failedChecks.map(r => `${r.filePath}: ${r.result.reason}`).join('; ');
            return {
                pass: false,
                reason: `以下文件审查未通过: ${reasons}`,
                commitMessage: ''
            };
        }

        // 所有文件都审查通过，进入汇聚阶段生成 commit message
        const commitMessages = successfulReviews
            .map(r => r.result.commitMessage)
            .filter(msg => msg && msg.trim())
            .map(msg => msg.trim());

        if (commitMessages.length === 0) {
            return {
                pass: true,
                reason: '所有文件审查通过',
                commitMessage: ''
            };
        }

        // 如果只有一个 commit message，直接使用，无需汇聚
        if (commitMessages.length === 1) {
            console.log(`=== 无需汇聚 ===`);
            console.log(`只有 1 个 commit message，直接使用: ${commitMessages[0]}`);
            console.log('---');
            return {
                pass: true,
                reason: '所有文件审查通过',
                commitMessage: commitMessages[0]
            };
        }

        // 多个 commit message，进入汇聚阶段
        console.log(`=== 进入汇聚阶段 ===`);
        console.log(`检测到 ${commitMessages.length} 个 commit messages，需要调用 LangChain 进行汇聚`);
        console.log('---');
        this.logger.info('所有文件审查通过，开始汇聚 commit messages');
        return await this.aggregateCommitMessages(commitMessages, successfulReviews);
    }

    // 新增：汇聚多个 commit message
    private async aggregateCommitMessages(commitMessages: string[], reviewResults: any[]): Promise<ReviewResult> {
        try {
            // 提取文件路径列表
            const filePaths = reviewResults.map(r => r.filePath);
            
            // 调用 Dify API 进行汇聚，传递 commit messages 和文件路径
            const result = await this.difyService.aggregateCommitMessages(commitMessages, filePaths);
            
            return {
                pass: true,
                reason: '所有文件审查通过',
                commitMessage: result.commitMessage || commitMessages[0] // 如果汇聚失败，使用第一个 message
            };
            
        } catch (error) {
            this.logger.error('汇聚 commit message 失败', error as Error);
            // 汇聚失败时，使用第一个 commit message
            return {
                pass: true,
                reason: '所有文件审查通过',
                commitMessage: commitMessages[0]
            };
        }
    }

    private async executeGitCommand(...args: string[]): Promise<string> {
        return new Promise((resolve, reject) => {
            const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
            if (!workspaceFolder) {
                resolve('');
                return;
            }

            const gitProcess = child_process.spawn('git', args, {
                cwd: workspaceFolder.uri.fsPath,
                stdio: ['pipe', 'pipe', 'pipe']
            });

            let stdout = '';
            let stderr = '';

            gitProcess.stdout.on('data', (data) => {
                stdout += data.toString();
            });

            gitProcess.stderr.on('data', (data) => {
                stderr += data.toString();
            });

            gitProcess.on('close', (code) => {
                if (code === 0) {
                    resolve(stdout);
                } else {
                    this.logger.error(`Git命令执行失败: ${stderr}`);
                    resolve(''); // 返回空字符串而不是reject，避免中断流程
                }
            });

            gitProcess.on('error', (error) => {
                this.logger.error('Git命令执行错误:', error);
                resolve(''); // 返回空字符串而不是reject，避免中断流程
            });
        });
    }

    private async updateCommitMessage(message: string) {
        const scm = vscode.scm.inputBox;
        if (scm) {
            scm.value = message;
        }
    }

    // 新增：自动commit方法
    private async executeGitCommitWithMessage(message: string) {
        try {
            if (!message.trim()) {
                vscode.window.showErrorMessage('Commit message 不能为空');
                return;
            }
            const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
            if (!workspaceFolder) {
                vscode.window.showErrorMessage('未找到工作区目录');
                return;
            }
            await this.executeGitCommand('commit', '-m', message);
        } catch (error) {
            vscode.window.showErrorMessage(`自动提交失败: ${error instanceof Error ? error.message : '未知错误'}`);
        }
    }

    public dispose() {
        this.disposables.forEach(d => d.dispose());
        this.statusBarItem.dispose();
    }
} 